<template>
  <div class="content-wrapp">
    <el-form ref="formData" :model="formData" size="small" label-width="60px">
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="formData.userName" placeholder="输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="jobStatus" v-if="columEnable">
        <el-select v-model="formData.jobStatus" filterable size="small">
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item,index) in statusList"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label-width="20px">
        <el-button type="primary" @click="getData" icon="el-icon-search">搜索</el-button>
        <el-button @click="resetForm('formData')" icon="el-icon-circle-close">清空</el-button>
      </el-form-item>
      <el-form-item label-width="10px">
        <el-button
          type="success"
          @click="$refs.user.add()"
          icon="el-icon-circle-plus-outline"
          size="small"
          v-if="addEnable"
        >新增人员</el-button>
        <el-button
          type="warning"
          @click="download"
          :disabled="downloadloading"
          :icon="downloadloading?'el-icon-loading':'el-icon-download'"
        >下载通讯录</el-button>
        <el-button
          type="warning"
          @click="download1"
          icon="el-icon-download"
        >下载模板</el-button>
        <el-button
          type="danger"
          :disabled="loadingTable"
          :icon="loadingTable?'el-icon-loading':'el-icon-upload2'"
          size="small"
          v-if="addEnable"
          @click="$refs.file.click()"
        >
          上传通讯录
          <input
            type="file"
            style="display: none;"
            id="file"
            ref="file"
            @change="upload(this)"
          />
        </el-button>
      </el-form-item>
      <el-form-item style="float: right;">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="formData.pageSize"
          :current-page.sync="formData.currentPage"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </el-form-item>
    </el-form>

    <el-table ref="table" :data="tableData" :header-cell-style="getRowClass" v-loading="loading">
      <el-table-column prop="employeeNumber" label="工号"></el-table-column>
      <el-table-column prop="userName" label="姓名"></el-table-column>
      <el-table-column prop="englishName" label="英文名"></el-table-column>
      <el-table-column prop="deptName" label="部门" width="160"></el-table-column>
      <el-table-column prop="postName" label="职位" width="150">
        <template slot-scope="scope">
          <span v-for="(item,index) in scope.row.posts" :key="index">
            {{item.postName}}
            <i v-if="scope.row.posts.length > index + 1">/</i>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="jobStatus" label="状态" width="100" v-if="columEnable">
        <template slot-scope="scope">
          <span class="jobStatus" v-if="scope.row.jobStatus">
            {{statusList.find(item => item.value == scope.row.jobStatus).label}}
            <i
              class="el-icon-edit"
              @click="$refs.statusModal.show(scope.row)"
            ></i>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="entryTime" label="入职时间" width="100" v-if="columEnable">
        <template slot-scope="scope">{{scope.row.entryTime | filtData}}</template>
      </el-table-column>
      <el-table-column prop="formalTime" label="转正时间" width="100" v-if="columEnable">
        <template slot-scope="scope">{{scope.row.formalTime | filtData}}</template>
      </el-table-column>
      <el-table-column prop="sex" label="性别">
        <template slot-scope="scope">{{scope.row.sex == 0?'男':'女'}}</template>
      </el-table-column>
      <el-table-column prop="maritalStatus" label="婚姻状况" v-if="columEnable">
        <template slot-scope="scope">{{scope.row.maritalStatus == 0?'未':'已'}}</template>
      </el-table-column>
      <el-table-column prop="identityNumber" label="身份证号" width="180" v-if="columEnable"></el-table-column>
      <el-table-column prop="identityValidity" label="身份证有效期" width="120" v-if="columEnable">
        <template slot-scope="scope">{{scope.row.identityValidity | filtData}}</template>
      </el-table-column>
      <el-table-column prop="birthDate" label="出生日期" width="100" v-if="columEnable">
        <template slot-scope="scope">{{scope.row.birthDate | filtData}}</template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" v-if="columEnable"></el-table-column>
      <el-table-column prop="politicCountenance" label="政治面貌" v-if="columEnable"></el-table-column>
      <el-table-column prop="nation" label="民族" v-if="columEnable"></el-table-column>
      <el-table-column prop="householdRegister" label="户籍" v-if="columEnable"></el-table-column>
      <el-table-column prop="nativePlace" label="籍贯" width="120" v-if="columEnable"></el-table-column>
      <el-table-column prop="permanentResidence" label="户口所在地址" width="280" v-if="columEnable"></el-table-column>
      <el-table-column prop="currentAddress" label="现居地址" width="280" v-if="columEnable"></el-table-column>
      <el-table-column prop="phoneNumber" label="联系方式" width="120"></el-table-column>
      <el-table-column prop="contractStartDate" label="合同开始日期" width="120" v-if="columEnable"></el-table-column>
      <el-table-column prop="contractEndDate" label="合同结束日期" width="120" v-if="columEnable"></el-table-column>
      <el-table-column prop="graduateSchool" label="毕业学校" width="140" v-if="columEnable"></el-table-column>
      <el-table-column prop="graduateTime" label="毕业时间" width="100" v-if="columEnable"></el-table-column>
      <el-table-column prop="degree" label="学历" width="120" v-if="columEnable"></el-table-column>
      <el-table-column prop="major" label="专业" width="170" v-if="columEnable"></el-table-column>
      <el-table-column prop="qualification" label="职业资格" v-if="columEnable"></el-table-column>
      <el-table-column prop="fundNumber" label="个人公积金账号" width="120" v-if="columEnable"></el-table-column>
      <el-table-column prop="socialSecurityNumber" label="社保账号" width="120" v-if="columEnable"></el-table-column>
      <el-table-column prop="emergencyContact" label="紧急联系人姓名" width="120" v-if="columEnable"></el-table-column>
      <el-table-column prop="emergencyContactPhone" label="紧急联系人号码" width="120" v-if="columEnable"></el-table-column>
      <el-table-column
        prop="emergencyContactAddress"
        label="紧急联系人地址"
        width="120"
        v-if="columEnable"
      ></el-table-column>
      <el-table-column fixed="right" label="操作" width="150" v-if="editEnabel || removeEnable">
        <template slot-scope="scope">
          <el-button
            type="success"
            size="mini"
            @click="$refs.user.edit(scope.row)"
            v-if="editEnabel"
          >编辑</el-button>
          <el-button
            type="danger"
            size="mini"
            @click="remove(scope.row.userId)"
            v-if="removeEnable"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <user-modal ref="user" @load="getData"></user-modal>
    <user-list ref="userList" @load="getData"></user-list>
    <status-modal ref="statusModal" @load="getData"></status-modal>
    <scrollTable ref="scrollTable"></scrollTable>
  </div>
</template>

<script>
import { formatDate } from "assets/js/date";
import userModal from "./userModal";
import userList from "./userList";
import statusModal from "./statusModal";
import { getUserInfo, removeUser } from "@/api/addressBook";
import scrollTable from "components/scroll/scroll-table.vue";
import { checkPermission } from "@/utils/permissions";
import { jobStatus } from "./jobStatus";

export default {
  components: {
    userModal,
    userList,
    scrollTable,
    statusModal,
  },
  data() {
    return {
      tableData: [],
      formData: {
        currentPage: 1,
        jobStatus: 1,
        pageSize: 20,
        userName: "",
      },
      total: 1,
      statusList: jobStatus(),
      loading: true,
      loadingTable: false,
      downloadloading:false,
      addEnable: checkPermission("system:userinfo:add"),
      editEnabel: checkPermission("system:userinfo:edit"),
      removeEnable: checkPermission("system:userinfo:delete"),
      columEnable: checkPermission("system:userinfo:colum"),
    };
  },
  filters: {
    filtData(time) {
      if (time) {
        let date = new Date(time);
        return formatDate(date, "yyyy-MM-dd");
      }
    },
  },
  created() {
    this.getData();
  },
  methods: {
    getData() {
      this.loading = true;
      getUserInfo(this.formData).then((res) => {
        this.tableData = res.data.data;
        this.loading = false;
        this.total = res.data.etxra;
        this.$refs.scrollTable.scrollShow(this.$refs.table);
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    remove(userId) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeUser({ id: userId }).then((res) => {
            if (res.data.code === this.ERR_OK) {
              this.$message.success("删除成功");
              this.getData();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {});
    },
    upload() {
      const that = this;
      this.file = event.currentTarget.files[0];
      var filetypes = [
        "application/vnd.ms-excel",
        "text/xml, application/xml",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "application/wps-office.xlsx",
        ".csv",
      ];
      if (this.file) {
        if (filetypes.indexOf(this.file.type) === -1) {
          this.$message.error("请上传.xlsx格式");
          return;
        }
        that.loadingTable = true;
        var rABS = false; //是否将文件读取为二进制字符串
        var f = this.file;
        var reader = new FileReader();

        FileReader.prototype.readAsBinaryString = function (f) {
          var binary = "";
          var rABS = false; //是否将文件读取为二进制字符串
          var pt = this;
          var wb; //读取完成的数据
          var outdata;
          var reader = new FileReader();
          reader.onload = function (e) {
            var bytes = new Uint8Array(reader.result);
            var length = bytes.byteLength;
            for (var i = 0; i < length; i++) {
              binary += String.fromCharCode(bytes[i]);
            }
            var XLSX = require("xlsx");
            if (rABS) {
              wb = XLSX.read(btoa(fixdata(binary)), {
                type: "base64",
              });
            } else {
              wb = XLSX.read(binary, {
                type: "binary",
              });
            }
            outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
            that.$refs.userList.show(outdata);
            that.loadingTable = false;
          };
          reader.readAsArrayBuffer(f);
        };
        if (rABS) {
          reader.readAsArrayBuffer(f);
        } else {
          reader.readAsBinaryString(f);
        }
      }
      this.$refs.file.value = "";
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 标题背景颜色
    getRowClass({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background: #EBEEF5 ";
      } else {
        return "";
      }
    },
    handleCurrentChange(cpage) {
      this.formData.currentPage = cpage;
      this.getData();
    },
    // 下载
    download() {
      this.downloadloading = true
      getUserInfo({
        jobStatus: this.formData.jobStatus,
        userName: this.formData.userName,
        currentPage: 1,
        pageSize: this.total,
      }).then((res) => {
        const row = [];
        res.data.data.forEach((el) => {
          el.jobStatus = this.statusList.find(
            (item) => item.value == el.jobStatus
          ).label;
          el.sex = el.sex == 0 ? "男" : "女";
          el.maritalStatus = el.maritalStatus == 0 ? "未" : "已";
          row.push(el);
        });
        this.export2Excel(row,'通讯录');
        this.downloadloading = false
      });
    },
    download1(){
      this.export2Excel([],'通讯录模板');
    },
    export2Excel(tableData,title) {
      var that = this;
      require.ensure([], () => {
        const { export_json_to_excel } = require("@/excel/Export2Excel"); //这里必须使用绝对路径
        const tHeader = []; // 导出的表头名
        const filterVal = []; // 导出的表头字段名
        const list = tableData;
        this.$refs.table.columns.forEach(item => {
          if(item.property){
             tHeader.push(item.label)
             filterVal.push(item.property)
          }
        })
        const data = that.formatJson(filterVal, list);
        export_json_to_excel(
          tHeader,
          data,
          title + formatDate(new Date(), "yyyy-MM-dd hh_mm")
        );
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
  },
};
</script> 
<style lang="scss" scoped>
.el-form-item {
  display: inline-block;
}
.jobStatus {
  i {
    margin-left: 3px;
    cursor: pointer;
  }
}
</style>